package com.seari.gena.ciosServer;

import java.nio.charset.Charset;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.seari.commonutils.redis.JedisUtilProxy;
import com.seari.gena.ciosServer.handler.CIOSServerHandler;
import com.seari.utils.PropertiesUtil;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

public class CIOSServer {
	protected static Logger logger = LoggerFactory.getLogger(CIOSServer.class);
	private final int port;

	public CIOSServer(int port) {
		this.port = port;
	}

	public void start() throws Exception {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			ServerBootstrap sb = new ServerBootstrap();
			sb.option(ChannelOption.SO_BACKLOG, 1024);
			sb.group(group, bossGroup) // 绑定线程池
					.channel(NioServerSocketChannel.class) // 指定使用的channel
					.childHandler(new ChannelInitializer<SocketChannel>() { // 绑定客户端连接时候触发操作

						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
							logger.info("客户端请求" + "IP:" + ch.localAddress().getHostName() + "Port:"
									+ ch.localAddress().getPort());
							ch.pipeline().addLast(new StringEncoder(Charset.forName("UTF-8")));
							ch.pipeline().addLast(new CIOSServerHandler()); // 客户端触发操作
							ch.pipeline().addLast(new ByteArrayEncoder());
							ch.pipeline().addLast(new ChunkedWriteHandler());
						}
					});
			ChannelFuture cf = sb.bind(port).sync(); // 服务器异步创建绑定
			if (cf.isDone()) {
			logger.info(CIOSServer.class + " 启动正在监听： " + cf.channel().localAddress());
			}
			cf.channel().closeFuture().sync(); // 关闭服务器通道
		} finally {
			group.shutdownGracefully().sync(); // 释放线程池资源
			bossGroup.shutdownGracefully().sync();
		}
	}

	public static void main(String[] args) throws Exception {
		JedisUtilProxy.initJedisPoolUtil("192.168.127.101", 6379);
		//JedisUtilProxy.initJedisPoolUtil("127.0.0.1", 6379);
		Properties prop = PropertiesUtil.loadConfig("gena.properties");
		new CIOSServer(Integer.parseInt(prop.getProperty("CIOSServerPort"))).start(); // 启动
	}
}
